<script setup lang="ts">
import { ElMessage, FormInstance } from 'element-plus';
import { reactive, ref } from 'vue';
import { invoke } from '@tauri-apps/api/core';
import { useRouter } from 'vue-router';
import { InternalRuleItem, Value } from "async-validator";
import { load_rtdata_subscriber_service_dxc, load_user_dxc, load_xcom_service_dxc } from '@/dxc';
import * as userService from "@/assets/api/userservice_0_0_1";
import * as xcomService from "@/assets/api/xcomservice_0_0_1";


const router = useRouter();
const loginFormRef = ref<FormInstance>();

const data = reactive<{
  showAdd: boolean // 用于判断当前是登录页，还是添加用户页
}>({
  showAdd: false
});

const loginFormModel = reactive<{
  account: string, // 账户名
  password: string  // 密码
  repassword: string  // 重复密码
  rememberPassword: boolean // 是否记住密码
}>({
  account: "",
  password: "",
  repassword: "",
  rememberPassword: false
});

// 登录函数
const onLogin = async () => {
  // 对输入参数进行验证
  const validate = await loginFormRef.value.validate();
  if (!validate) {
    return;
  }
  // 登录

  // 登录成功，跳转到行情页面
  router.push("/quotes");
};

// 添加账号
const onAddAccount = async () => {
  // 对输入参数进行验证

  // 调用接口添加账号
    const res = await userService.AddUser({
    username: loginFormModel.account,
    password: loginFormModel.password,
    remember: false,
  });
  if (res.err_code !== 0) {
    ElMessage.error(res.err_msg);
    return;
  }
  // 登录成功
  data.showAdd = false;
};


// 验证两次密码是否一致
const rePassValidator = (rule: InternalRuleItem, value: Value, callback: (error?: string | Error) => void) => {
  if (value === loginFormModel.password) {
    callback();
  } else {
    callback(new Error("两次输入密码不同"));
  }
};

// 加载上一次登录时记住的密码
const loadRemomberPassword = async () => {
  const res = await userService.GetRememberAccount();
  console.log(res);
  if (res.err_code !== 0 || !res.data) {
    return;
  }
  if (res.data.username) {
    loginFormModel.rememberPassword = true;
    loginFormModel.account = res.data.username;
    loginFormModel.password = res.data.password;
  }
};

const connectToRealtimeNode = async()=>{
  const res = await xcomService.BuildChannel({
    node_url: "dxm://127.0.0.1:8090",
    is_keep: true
  });

  console.log(res);
};

// 初始化 xPort
const onInitxPort = async () => {
  const is_init = await invoke("is_init_xport");
  if (!is_init) {
    await invoke("boot_xport");
    await load_xcom_service_dxc();
    console.log("加载用户组件。。。")
    await load_user_dxc();
    console.log("加载行情组件。。。")
    await load_rtdata_subscriber_service_dxc();
    //
    await connectToRealtimeNode();
  }
};
// 进入页面，开始初始化
const onInit = async () => {
  await onInitxPort();
  await loadRemomberPassword();
};

onInit();
</script>

<template>
  <el-form ref="loginFormRef" :model="loginFormModel" label-position="top">
    <el-form-item prop="account" label="" :rules="[
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ]">
      <el-input v-model="loginFormModel.account" placeholder="请输入用户名/手机号" />
    </el-form-item>

    <el-form-item prop="password" label="" :rules="[
    { required: true, message: '密码不能为空', trigger: 'blur' }
  ]">
      <el-input type="password" v-model="loginFormModel.password" placeholder="请输入密码" />
    </el-form-item>


    <div v-if="!data.showAdd" class="horzontal-center-layout ">
      <el-checkbox label="记住密码" v-model="loginFormModel.rememberPassword" />
    </div>

    <el-form-item v-else prop="repassword" label="" :rules="[{ required: true, message: '密码不能为空', trigger: 'blur' },
  { required: true, validator: rePassValidator, message: '确认密码（8至16位数英文数字组合）且与密码相同', trigger: 'blur' }]">
      <el-input type="password" v-model="loginFormModel.repassword" placeholder="再次输入密码" />
    </el-form-item>


    <div v-if="!data.showAdd" class="horzontal-center-layout account-login-btn-bar ">
      <el-button class="login-btn" @click="onLogin">登录</el-button>
    </div>

    <div v-else class="horzontal-center-layout account-login-btn-bar ">
      <el-button class="login-btn" @click="onAddAccount">注册账号</el-button>
    </div>

    <div class="bottom-bar horzontal-center-layout flex-center">
      <div v-if="!data.showAdd" class="add-account" @click="data.showAdd = true"> 注册账号</div>
      <div v-else class="add-account" @click="data.showAdd = false"> 账号登录</div>
      <div class="spliter"></div>
    </div>
  </el-form>

</template>


<style scoped lang="scss">
.account-form {
  margin-top: 30px;
  padding: 0 30px;
  :deep(.el-form-item__label) {
    font-weight: bold;
    margin-bottom: 0px !important;
  }
  :deep(.el-input__wrapper) {
    padding: 4px 10px;
    border-top: none;
    border-left: none;
    border-right: none;
    border-radius: 6px;
    outline: none;
    box-shadow: none;
  }
  >img {
    width: 49px;
    height: 49px;
    display: block;
    margin-bottom: 40px;
  }
  .forget-btn {
    &:hover {
      color: #2F49D0;
    }
  }
  .account-login-btn-bar {
    margin-top: 20px;
  }
  .login-btn,
  .register-btn {
    width: 100%;
    height: 36px;
    border-radius: 6px;
    display: inline-block;
    font-size: 14px;
    border: none;
    background-color: transparent;
    background-size: 100% 100%;
    outline: none;
  }
  .login-btn {
    color: white;
    background: #515a6e;
    &:hover {
      background: #515a6e;
    }
  }
  .bottom-bar {
    margin-top: 30px;
    color: #515a6e;
    .spliter {
      margin: 0 10px;
    }
    .add-account {
      cursor: pointer;
      &:hover {
        color: #043885;
      }
    }
  }
}
</style>